<?php

namespace App\Http\Controllers;

// 自动加载类
require_once __DIR__ .'/../../GatewayWorker/vendor/autoload.php';//引入绝对路径上的GatewayWorker组件上的自动加载类,不然回报找不到"GatewayClient\Gateway"的错误,或者你也可以在项目更目录composer安装"GatewayClient\Gateway"这个

use App\FriendList;
use App\ImUser;
use GatewayClient\Gateway;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Im控制器
 * Class ImController
 * @package App\Http\Controllers
 */
class ImController extends Controller
{
    /**
     * 好友列表
     */
    public function indexList()
    {
        $user = session('user');
        $data = FriendList::where('user_id', $user['id'])->paginate(20);
        return view('im.indexList', compact('data'));
    }

    /**
     * 添加好友
     * @param Request $request
     */
    public function addFriends(Request $request)
    {
        $friend_id = ImUser::where('tel', $request->tel)->value('id');
        $user = session('user');
        if ($friend_id) {
            //对方id存在
            $is_friend = FriendList::where([
                ['user_id', $user['id']],
                ['friend_id', $friend_id],
            ])->exists();
            if(!$is_friend){
                FriendList::create([
                    'user_id'=>$user['id'],
                    'friend_id'=>$friend_id,
                ]);
                FriendList::create([
                    'user_id'=>$friend_id,
                    'friend_id'=>$user['id'],
                ]);
                return redirect()->route('im.indexList');
            }
        }
        dd('对方手机号有误');
    }

    /**
     * 删除好友
     * @param $id
     */
    public function deleteFriends($friend_lists_id){
        $friendList = FriendList::where('id',$friend_lists_id)->first();

        DB::beginTransaction();
        try{
            $del_1 = FriendList::where([
                ['user_id',$friendList['user_id']],
                ['friend_id',$friendList['friend_id']]
            ])->delete();
            $del_2 = FriendList::where([
                ['user_id',$friendList['friend_id']],
                ['friend_id',$friendList['user_id']]
            ])->delete();
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            dd('删除失败:' . $exception->getMessage());
        }

        if($del_1 && $del_2){
            return redirect()->back();
        }
        dd('删除失败');
    }

    /**
     * 聊天页面
     * @param Request $request
     * @param $friend_id 好友id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function chat(Request $request, $friend_id)
    {
        return view('im.chat',compact('friend_id'));
    }

    /**
     * 绑定用户
     * @param Request $request
     */
    public function binding(Request $request){
        $client_id = $request->client_id;//GatewayWorker 给我们分配的连接id
        $user = session('user');
        $uid  = $user['id'];//我在我方数据库IM用户表中的主键id
        Gateway::bindUid($client_id,$uid);
        $message = [
            'type' => 'binding_success',
            'msg' => '绑定成功'
        ];
        Gateway::$registerAddress = '127.0.0.1:1238';
        Gateway::sendToUid($uid, json_encode($message));//向任意uid的网站页面发送数据
        $message['code'] = 200;
        $message['success'] = 1;//1:成功,0:失败
        return json_encode($message);
    }

    /**
     * 发送消息
     * @param Request $request->recipients_id 收件人id,在我方friend_lists好友表中的friend_id字段值
     * @param Request $request->type 信息类型 string:文字信息,img:图片
     * @param Request $request->msg 信息内容
     */
    public function sendMessage(Request $request){
        $post = $request->all();
        $user = session('user');
        $user_id = $user['id'];
        $message = [
            'type' => $request->type,
            'addresser_id' => $user_id,//发件人id
            'recipients_id' => $post['recipients_id'],//收件人id
            'msg' => $post['msg'],
        ];
        //检测是不是文件,是的话给文件一个随机生成的文件id,方便前端操作
        switch ($request->type){
            case 'img':
                $message['file_id'] = time() . rand(10,99);//文件id
                break;
            default:
                $message['file_id'] = '';
                break;
        }
        Gateway::$registerAddress = '127.0.0.1:1238';
        Gateway::sendToUid($post['recipients_id'], json_encode($message));//给发件人的uid网站页面发送数据
        $message['code'] = 200;
        $message['success'] = 1;//1:成功,0:失败
        return json_encode($message);
    }
}
